# -*- coding: utf-8 -*-
from __future__ import division
from __future__ import print_function

from ..ops import Ref, Mean, Abs, Greater
from ..base import OpsFeature

from .close import Close

class RSI(OpsFeature):
    """Technical Indicator - RSI

    - RSI = SMA(MAX(CLOSE - REF(CLOSE, 1), 0), N) / SMA(ABS(CLOSE - REF(CLOSE, 1)), N) * 100
    """
    def __init__(self, feature=None, N=12):
        self.feature = feature or Close()
        self.N = N

    def __str__(self):
        name = type(self).__name__.lower()
        if str(self.feature) != 'close':
            name += '_'+str(self.feature)
        if self.N != 12:
            name += '_'+str(self.N)
        return name
    
    def _load_internal(self, instrument, start_time, end_time, freq):
        diff = self.feature - Ref(self.feature, 1)
        rsi = Mean(Greater(diff, 0), self.N) / Mean(Abs(diff), self.N) * 100
        return rsi.load(instrument, start_time, end_time, freq)
